package com.seventh.blekit;

import androidx.annotation.NonNull;
import androidx.annotation.Size;

/**
 * @author chengxin
 * create at 2021/5/21
 * description:
 */
public class SensorData {
    //四元数
    public final float p0;
    public final float p1;
    public final float p2;
    public final float p3;


    public final float gx;
    public final float gy;
    public final float gz;
    //内部温度
    public final float power;

    private SensorData(float p0, float p1, float p2, float p3, float gx, float gy, float gz, float power) {
        this.p0 = p0;
        this.p1 = p1;
        this.p2 = p2;
        this.p3 = p3;
        this.gx = gx;
        this.gy = gy;
        this.gz = gz;
        this.power = power;
    }

    public static SensorData create(@Size(19) byte[] value) {
        return new SensorData(
                func(value[2], value[3]),
                func(value[4], value[5]),
                func(value[6], value[7]),
                func(value[8], value[9]),
                func(value[10], value[11]) * 10,
                func(value[12], value[13]) * 10,
                func(value[14], value[15]) * 10,
                value[1]

        );
    }

    @NonNull
    @Override
    public String toString() {
        return "p0:" +
                p0 +
                ",\n" +
                "p1:" +
                p1 +
                ",\n" +
                "p2:" +
                p2 +
                ",\n" +
                "p3:" +
                p3 +
                ",\n" +
                "gx:" +
                gx +
                ",\n" +
                "gy:" +
                gy +
                ",\n" +
                "gz:" +
                gz +
                ",\n" +
                "power:" +
                power;
    }

    /**
     * 第一位带符号，第二位不带符号
     */
    private static float func(byte bt0, byte bt1) {
        byte a = (byte) (bt0 & 0x80);
        int reset = Integer.parseInt(byteToString(bt1), 16);
        if (a != 0) {
            byte bt00 = (byte) (bt0 & 0x7f);
            return -((float) (bt00 * 256 + reset)) / 1000f;
        } else {
            return ((float) (bt0 * 256 + reset)) / 1000f;
        }
    }

    private static String byteToString(byte value) {
        String hex = Integer.toHexString(value & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }
}
